package org.bird.reference;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;

/**
 * 弱引用:下次垃圾回收将会被回收
 * 
 * @author liangjf
 *
 */
public class WeakReference {

	private static ReferenceQueue<VeryBig> rq = new ReferenceQueue<VeryBig>();

	public static void main(String args[]) {
		WeakReference rf = new WeakReference();
		int size = 3;
		LinkedList<java.lang.ref.WeakReference<VeryBig>> weakList = new LinkedList<java.lang.ref.WeakReference<VeryBig>>();
		for (int i = 0; i < size; i++) {
			weakList.add(rf.new VeryBigWeakReference(rf.new VeryBig("Weak " + i), rq));
			System.out.println("Just created weak: " + weakList.getLast());

		}
		for(int i = 0; i < weakList.size(); i++) {
			Reference<? extends VeryBig> ref = weakList.get(i);
			System.out.println("In List: " + ((VeryBigWeakReference) (ref)).id + "&&" + ref + "&&" + ref.get());
		}
		System.gc();
		try { // 下面休息几分钟，让上面的垃圾回收线程运行完成
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		checkQueue();
	}

	public static void checkQueue() {
		Reference<? extends VeryBig> ref = null;
		while ((ref = rq.poll()) != null) {
			if (ref != null) {
				System.out.println("In queue: " + ((VeryBigWeakReference) (ref)).id + "&&" + ref + "&&" + ref.get());
			}
		}
	}

	class VeryBig {
		public String id;
		// 占用空间,让线程进行回收
		byte[] b = new byte[2 * 1024];

		public VeryBig(String id) {
			this.id = id;
		}

		protected void finalize() {
			System.out.println("Finalizing VeryBig " + id);
		}
	}

	class VeryBigWeakReference extends java.lang.ref.WeakReference<VeryBig> {
		public String id;

		public VeryBigWeakReference(VeryBig big, ReferenceQueue<VeryBig> rq) {
			super(big, rq);
			this.id = big.id;
		}

		protected void finalize() {
			System.out.println("Finalizing VeryBigWeakReference " + id);
		}
	}
}
